//! 数据网关监控插件系统
//! 
//! 提供全面的监控和可观测性功能：
//! - 指标收集和导出
//! - 健康检查
//! - 性能监控
//! - 告警管理

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use anyhow::Result;

pub mod metrics;
pub mod health;
pub mod alerts;
pub mod system;
pub mod exporter;

pub use metrics::{MetricsCollector, MetricType, MetricValue, MetricData};
pub use health::{HealthChecker, HealthStatus, HealthCheck, ComponentHealth};
pub use alerts::{AlertManager, AlertRule, AlertLevel, Alert};
pub use system::{SystemMonitor, SystemMetrics, ResourceUsage};
pub use exporter::{PrometheusExporter, MetricsExporter};

/// 监控配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
    /// 是否启用监控
    pub enabled: bool,
    /// 指标收集间隔（秒）
    pub metrics_interval: u64,
    /// 健康检查间隔（秒）
    pub health_check_interval: u64,
    /// Prometheus导出配置
    pub prometheus_config: Option<PrometheusConfig>,
    /// 告警配置
    pub alert_config: Option<AlertConfig>,
    /// 系统监控配置
    pub system_config: Option<SystemMonitorConfig>,
}

/// Prometheus配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrometheusConfig {
    /// 监听地址
    pub listen_address: String,
    /// 监听端口
    pub port: u16,
    /// 指标路径
    pub metrics_path: String,
    /// 是否启用
    pub enabled: bool,
}

/// 告警配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertConfig {
    /// 是否启用告警
    pub enabled: bool,
    /// 告警规则文件路径
    pub rules_file: Option<String>,
    /// Webhook URL
    pub webhook_url: Option<String>,
    /// 邮件配置
    pub email_config: Option<EmailConfig>,
}

/// 邮件配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmailConfig {
    /// SMTP服务器
    pub smtp_server: String,
    /// SMTP端口
    pub smtp_port: u16,
    /// 用户名
    pub username: String,
    /// 密码
    pub password: String,
    /// 发件人
    pub from: String,
    /// 收件人列表
    pub to: Vec<String>,
}

/// 系统监控配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemMonitorConfig {
    /// 是否启用系统监控
    pub enabled: bool,
    /// CPU监控阈值（百分比）
    pub cpu_threshold: f64,
    /// 内存监控阈值（百分比）
    pub memory_threshold: f64,
    /// 磁盘监控阈值（百分比）
    pub disk_threshold: f64,
}

/// 监控管理器
pub struct MonitoringManager {
    /// 配置
    config: MonitoringConfig,
    /// 指标收集器
    metrics_collector: Arc<MetricsCollector>,
    /// 健康检查器
    health_checker: Arc<HealthChecker>,
    /// 告警管理器
    alert_manager: Option<Arc<AlertManager>>,
    /// 系统监控器
    system_monitor: Option<Arc<SystemMonitor>>,
    /// Prometheus导出器
    prometheus_exporter: Option<Arc<PrometheusExporter>>,
}

impl MonitoringManager {
    /// 创建新的监控管理器
    pub async fn new(config: MonitoringConfig) -> Result<Self> {
        let metrics_collector = Arc::new(MetricsCollector::new());
        let health_checker = Arc::new(HealthChecker::new());

        let alert_manager = if let Some(alert_config) = &config.alert_config {
            if alert_config.enabled {
                Some(Arc::new(AlertManager::new(alert_config.clone()).await?))
            } else {
                None
            }
        } else {
            None
        };

        let system_monitor = if let Some(system_config) = &config.system_config {
            if system_config.enabled {
                Some(Arc::new(SystemMonitor::new(system_config.clone())))
            } else {
                None
            }
        } else {
            None
        };

        let prometheus_exporter = if let Some(prometheus_config) = &config.prometheus_config {
            if prometheus_config.enabled {
                Some(Arc::new(PrometheusExporter::new(prometheus_config.clone()).await?))
            } else {
                None
            }
        } else {
            None
        };

        Ok(Self {
            config,
            metrics_collector,
            health_checker,
            alert_manager,
            system_monitor,
            prometheus_exporter,
        })
    }

    /// 启动监控服务
    pub async fn start(&self) -> Result<()> {
        if !self.config.enabled {
            tracing::info!("监控功能已禁用");
            return Ok(());
        }

        tracing::info!("启动监控服务");

        // 启动指标收集
        self.start_metrics_collection().await?;

        // 启动健康检查
        self.start_health_checks().await?;

        // 启动系统监控
        if let Some(system_monitor) = &self.system_monitor {
            system_monitor.start().await?;
        }

        // 启动Prometheus导出器
        if let Some(prometheus_exporter) = &self.prometheus_exporter {
            prometheus_exporter.start().await?;
        }

        tracing::info!("监控服务启动完成");
        Ok(())
    }

    /// 停止监控服务
    pub async fn stop(&self) -> Result<()> {
        tracing::info!("停止监控服务");

        // 停止各个组件
        if let Some(prometheus_exporter) = &self.prometheus_exporter {
            prometheus_exporter.stop().await?;
        }

        if let Some(system_monitor) = &self.system_monitor {
            system_monitor.stop().await?;
        }

        tracing::info!("监控服务停止完成");
        Ok(())
    }

    /// 启动指标收集
    async fn start_metrics_collection(&self) -> Result<()> {
        let collector = self.metrics_collector.clone();
        let interval = Duration::from_secs(self.config.metrics_interval);

        tokio::spawn(async move {
            let mut interval_timer = tokio::time::interval(interval);
            loop {
                interval_timer.tick().await;
                if let Err(e) = collector.collect_metrics().await {
                    tracing::error!("指标收集失败: {}", e);
                }
            }
        });

        Ok(())
    }

    /// 启动健康检查
    async fn start_health_checks(&self) -> Result<()> {
        let checker = self.health_checker.clone();
        let interval = Duration::from_secs(self.config.health_check_interval);

        tokio::spawn(async move {
            let mut interval_timer = tokio::time::interval(interval);
            loop {
                interval_timer.tick().await;
                if let Err(e) = checker.run_health_checks().await {
                    tracing::error!("健康检查失败: {}", e);
                }
            }
        });

        Ok(())
    }

    /// 记录指标
    pub async fn record_metric(&self, name: &str, value: MetricValue, labels: HashMap<String, String>) -> Result<()> {
        self.metrics_collector.record_metric(name, value, labels).await
    }

    /// 注册健康检查
    pub async fn register_health_check(&self, check: HealthCheck) -> Result<()> {
        self.health_checker.register_check(check).await
    }

    /// 获取健康状态
    pub async fn get_health_status(&self) -> Result<HealthStatus> {
        self.health_checker.get_overall_status().await
    }

    /// 获取指标数据
    pub async fn get_metrics(&self) -> Result<Vec<MetricData>> {
        self.metrics_collector.get_metrics().await
    }

    /// 触发告警
    pub async fn trigger_alert(&self, alert: Alert) -> Result<()> {
        if let Some(alert_manager) = &self.alert_manager {
            alert_manager.trigger_alert(alert).await?;
        }
        Ok(())
    }

    /// 获取系统指标
    pub async fn get_system_metrics(&self) -> Result<Option<SystemMetrics>> {
        if let Some(system_monitor) = &self.system_monitor {
            Ok(Some(system_monitor.get_metrics().await?))
        } else {
            Ok(None)
        }
    }
}

impl Default for MonitoringConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            metrics_interval: 30,
            health_check_interval: 60,
            prometheus_config: Some(PrometheusConfig {
                listen_address: "0.0.0.0".to_string(),
                port: 9090,
                metrics_path: "/metrics".to_string(),
                enabled: true,
            }),
            alert_config: None,
            system_config: Some(SystemMonitorConfig {
                enabled: true,
                cpu_threshold: 80.0,
                memory_threshold: 85.0,
                disk_threshold: 90.0,
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_monitoring_config_default() {
        let config = MonitoringConfig::default();
        assert!(config.enabled);
        assert_eq!(config.metrics_interval, 30);
        assert_eq!(config.health_check_interval, 60);
        assert!(config.prometheus_config.is_some());
        assert!(config.system_config.is_some());
    }

    #[tokio::test]
    async fn test_monitoring_manager_creation() {
        let config = MonitoringConfig::default();
        let manager = MonitoringManager::new(config).await.unwrap();
        
        // 测试基本功能
        let health_status = manager.get_health_status().await.unwrap();
        assert!(matches!(health_status, HealthStatus::Healthy | HealthStatus::Degraded | HealthStatus::Unhealthy));
    }
}
